<template>
	<a-card :bordered="false" style="margin-bottom: 10px" :accept="uploadAccept">
		<a-spin :spinning="spinning" :delay="delayTime">
			<a-upload-dragger :file-list="fileList" :before-upload="beforeUpload" :maxCount="1">
				<p class="ant-upload-drag-icon">
					<inbox-outlined></inbox-outlined>
				</p>
				<p class="ant-upload-text">点击或者拖拽文件到此区域上传文件</p>
				<p class="ant-upload-hint">
					如果您不知道需要导入的数据格式，可以点击<a @click.stop="downTemplate">此处</a>下载模板
				</p>
			</a-upload-dragger>
		</a-spin>
	</a-card>
</template>
<script setup name="ImportBasic">
	import file from '@/utils/file'
	import { message } from 'ant-design-vue'
	const spinning = ref(false) //加载中
	const delayTime = 100 //延迟显示加载效果的时间（防止闪烁）
	const props = defineProps(['api']) //props
	const fileList = ref([]) //文件列表
	// 打开抽屉
	const onOpen = () => {}
	//上传之前
	const beforeUpload = (file) => {
		fileList.value = [file]
		return false
	}
	//下载模板
	const downTemplate = () => {
		props.api
			.template()
			.then((res) => {
				file.downLoadFile(res)
			})
			.finally(() => {})
	}

	//允许上传的文件类型
	const fileAccept = [
		{
			extension: '.xlsx',
			mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
		}
	]
	// 指定能选择的文件类型
	const uploadAccept = String(
		fileAccept.map((item) => {
			return item.mimeType
		})
	)
	// 验证并提交数据
	const onSubmit = () => {
		spinning.value = true
		const fileData = new FormData()
		if (fileList.value.length === 0) {
			message.warning('请先选择文件！')
			return new Promise((resolve, reject) => {
				spinning.value = false
				reject()
			})
		} else {
			// 校验上传文件扩展名和文件类型是否为.xls、.xlsx
			const extension = '.'.concat(fileList.value[0].name.split('.').slice(-1).toString().toLowerCase())
			const mimeType = fileList.value[0].type
			// 提取允许的扩展名
			const extensionArr = fileAccept.map((item) => item.extension)
			// 提取允许的MIMEType
			const mimeTypeArr = fileAccept.map((item) => item.mimeType)
			if (!extensionArr.includes(extension) || !mimeTypeArr.includes(mimeType)) {
				message.warning('上传文件类型仅支持xlsx格式文件！')
				return new Promise((resolve, reject) => {
					fileList.value = []
					spinning.value = false
					reject()
				})
			}
			fileData.append('file', fileList.value[0])
			if (props.maxRowsCount) {
				fileData.append('maxRowsCount', props.maxRowsCount)
			}
			return new Promise((resolve, reject) => {
				props.api
					.preview(fileData)
					.then((data) => {
						resolve(data)
					})
					.finally(() => {
						fileList.value = []
						spinning.value = false
					})
			})
		}
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onSubmit,
		onOpen
	})
</script>
<style scoped></style>
